<?php
/*
 * 上传处理类
 * */
class Upload{ 
    private $name='';//含有扩展名
    private $mime='';//MIME,image/jpeg
    private $tmp_abspath='';
    private $error=null;
    private $size=0;
    private $base='template/uploads/';//上传基本路径
    private $topath='';  //上传路径
    private $width='';
    private $height='';
    private $extend='';
    private $newFile='';
    
    
    public function __construct($field){
        $this->upload($field);
    }
    
    public function upload($field){
        //当未选择图片提交时，$_FILES数组中相应字段为空字符串error为非零值
        if ($field && !$_FILES[$field]['error']){
            $this->name=$_FILES[$field]['name'];
            $this->mime=$_FILES[$field]['type'];
            $this->tmp_abspath=$_FILES[$field]['tmp_name'];
            $this->error=$_FILES[$field]['error'];
            $this->size=$_FILES[$field]['size'];
            /* 
             * 0 => 1024,
             * 1 => 768,
             * 2 => 2,
             * 3 => 'width="1024" height="768"',
             * 'bits' => 8,
             * 'channels' => 3,
             * 'mime' => 'image/jpeg',
             * */
            $img=getimagesize($this->tmp_abspath);
            $this->width=$img[0];
            $this->height=$img[1];
            /*
             * 1 = GIF，2 = JPG，3 = PNG，4 = SWF，5 = PSD，6 = BMP，
             * 7 = TIFF(intel byte order,字节序)，8 = TIFF(motorola byte order，字节序)，
             * 9 = JPC，10 = JP2，11 = JPX，12 = JB2，13 = SWC，14 = IFF，
             * 15 = WBMP，16 = XBM
             */
            $extends=array('GIF','JPG','PNG','SWF','PSD','BMP','TIFF','TIFF','JPC','JP2','JPX','12'=>'JB2',
                         'SWC','IFF','WBMP','XBM'
                     );
            $this->extend=$extends[$img[2]-1];
        }
    }
    
    public function doUpload(){
            $newName=md5(time().rand(0,1));
            $newFilePath=$this->base.$this->topath;
            if (!is_dir(APP_PATH.$newFilePath))
                throw new Exception('目录不存在');
            $this->newFile=$newFilePath.$newName.'.'.$this->extend;
            if (!move_uploaded_file($this->tmp_abspath,APP_PATH.$this->newFile)){
                throw new Exception('上传发生错误');
            }
    }

    public function path($path=''){
        if ($path==''){
            return $this->base.$this->topath;
        }else {
            $this->topath=trim($path,'/').'/';
        }
    }
    
    public function getFile(){
        return $this->newFile;
    }



}